package com.wocao.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wocao.entity.ReqBody;
import com.wocao.entity.ZyCommunity;
import com.wocao.mapper.ZyCommunityMapper;
import com.wocao.service.ZyCommunityService;
import com.wocao.utils.ExcelUtil;
import com.wocao.utils.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 小区  服务实现类
 *
 * @since 2023-11-29
 */
@Service
public class ZyCommunityServiceImpl extends ServiceImpl<ZyCommunityMapper, ZyCommunity> implements ZyCommunityService {

    @Autowired
    private ZyCommunityMapper zyCommunityMapper;


    @Override
    public Page<ZyCommunity> selectAllZyCommunitys(Page page, ReqBody reqBody) {
        return zyCommunityMapper.selectAllZyCommunitys(page,reqBody);
    }

    @Override
    public void areaAdd(ZyCommunity zyCommunity) {
        zyCommunity.setCreateTime(LocalDateTime.now());
        Random random = new Random();
        StringBuilder builder = new StringBuilder("COMMUNITY_");
        for (int i = 0; i < 13; i++) {
            int shu = random.nextInt(10);
            builder.append(shu);
        }
        zyCommunity.setCommunityCode(builder.toString());
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(8, 1);
        long nextId = idWorker.nextId();
        zyCommunity.setCommunityId(nextId);
        zyCommunityMapper.insert(zyCommunity);
    }

    @Override
    public void communityEdit(ZyCommunity zyCommunity) {
        zyCommunity.setUpdateTime(LocalDateTime.now());
        zyCommunityMapper.updateById(zyCommunity);
    }

    @Override
    public void derive(HttpServletResponse response, String[] communityIds) throws IOException {
        List<ZyCommunity> zyCommunityList = new ArrayList<>();
        for (int i = 0; i < communityIds.length; i++) {
            ZyCommunity zyCommunity = zyCommunityMapper.selectCommunityById(communityIds[i]);
            zyCommunityList.add(zyCommunity);
        }
        ExcelUtil.export(response,ZyCommunity.class,zyCommunityList);
    }

    @Override
    public List<ZyCommunity> selectAllByOwnerId(String userId) {
        return zyCommunityMapper.selectAllByOwnerId(userId);
    }

    @Override
    public void editDeptId(String communityId, String deptId) {
        zyCommunityMapper.editDeptId(communityId,deptId);
    }


}
